﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Admin.Domain;
using Windows.Admin.Infrastructure.EFCore;
using Windows.Admin.Infrastructure.EFCore.Extensions;
using Windows.Infrastructure.Share.Extensions;
using Windows.Infrastructure.Share.Security;

namespace Windows.Admin.Service
{
    public class SystemService : ISystemService
    {
        private readonly IUserService _userSvc;
        private readonly IAppService _appSvc;
        private readonly IPrivilegeService _privilegeSvc;
        private readonly ICurrentUser _currentUser;
        private readonly AdminDbContext _db;
        private readonly IMapper _mapper;
        public SystemService(IPrivilegeService privilegeSvc, IAppService appSvc, IUserService userSvc, ICurrentUser currentUser,AdminDbContext db, IMapper mapper)
        {
            _privilegeSvc = privilegeSvc;
            _appSvc = appSvc;
            _userSvc = userSvc;
            _currentUser = currentUser;
            _db = db;
            _mapper = mapper;
        }
        /// <summary>
        /// 初始化系统
        /// </summary>
        /// <returns></returns>
        public async Task<SystemResponse> Init()
        {
            List<App> apps;

            int[] types = {AppTypeEnum.Catalog.ToInt(), AppTypeEnum.App.ToInt() };
            if (_currentUser.IsAdmin)
            {
                apps = await _db.App.GetBasicApps(types).ToListAsync();
            }
                
            else
            {
                var privileges = await _privilegeSvc.GetCurrentUserPrivileges();
                var appIds = privileges.Where(x => x.Access == AccessEnum.App.ToString()).Select(s => s.AccessValue).ToList();
                apps = await _db.App.GetBasicApps(types).Where(x => appIds.Contains(x.Id)).ToListAsync();
            }
            SystemResponse system = new()
            {
                UserInfo = await _userSvc.CurrentUser(),
                Apps = _mapper.Map<List<AppResponse>>(apps),
                Shortcuts = await _appSvc.GetCurrentUserShortuts(),
                Licenses = await _privilegeSvc.GetCurrentUserLicenses()
            };
            return system;
        }
    }
}
